package com.zxl.manager.privacy.utils.track.crash;

import android.content.Context;
import android.text.TextUtils;

import com.zxl.manager.privacy.utils.utils.LogUtils;

import java.util.Properties;

/**
 * Created by Administrator on 2016/8/26.
 */
public class CrashReport implements Thread.UncaughtExceptionHandler {

    private static final String DEVICES_DATA_KEY = "devicesData";

    private static final String CUSTOM_DATA_KEY = "CustomData";

    private Context mContext;

    private String mLogPath;

    private String mChannel;

    public CrashReport(Context mContext, String mLogPath, String mChannel) {
        this.mContext = mContext;
        this.mLogPath = mLogPath;
        this.mChannel = mChannel;
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        try {
            Properties properties = exception(thread.getName(), ex);
            String reportFile = ExceptionUtils.saveCrashReportFile(mLogPath, properties);
            CrashReportService.saveCrashRecord(reportFile);
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            android.os.Process.killProcess(android.os.Process.myPid());
        }
    }

    public Properties exception(String message, Throwable ex) {
        String excepitonData = null;
        if (null != ex) {
            excepitonData = ExceptionUtils.getStackTraceString(ex);
            LogUtils.e(excepitonData);
        }

        if (!TextUtils.isEmpty(message)) {
            if (excepitonData == null) {
                excepitonData = message;
            } else {
                excepitonData = message + "\\n" + excepitonData;
            }
        }
        Properties mCrashProperties = new Properties();
        mCrashProperties.put(ExceptionUtils.STACK_TRACE_KEY, excepitonData);
        Properties retrieveCrashData = DevicesUtils.retrieveCrashData(mContext, "", mChannel);
        mCrashProperties.put(DEVICES_DATA_KEY, retrieveCrashData.toString());
        String customData = CrashReportManager.getInstance().customData;
        if (!TextUtils.isEmpty(customData)) {
            mCrashProperties.put(CUSTOM_DATA_KEY, customData);
        }
        return mCrashProperties;
    }
}
